﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Util
{
    public static class StringExtensions
    {
        /// <summary>
        /// Escapes a string so that it is suitable to be embedded in XML as
        /// text.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        /// <remarks>
        /// The following characters in the original string are replaced:
        /// < => &lt;
        /// > => &gt;
        /// " => &quot;
        /// ' => &apos;
        /// & => &amp;
        /// </remarks>
        public static string EscapeXml(this string s)
        {
            return System.Security.SecurityElement.Escape(s);
        }

        public static string UnescapeXml(this string s)
        {
            if (s == null || s.IndexOf('&') < 0)
                return s;

            StringBuilder sb = new StringBuilder(s);
            sb.Replace("&lt;", "<");
            sb.Replace("&gt;", ">");
            sb.Replace("&quot;", "\"");
            sb.Replace("&apos;", "'");
            sb.Replace("&amp;", "&");
            return sb.ToString();
        }
    }
}
